package cate.game.pvp.guildwar.data.base;

import cate.common.table.d.GDGuildWar;
import cate.common.table.pvp.guildwar.row.GuildWarTimeRow;
import cate.common.table.pvp.guildwar.sheet.GuildWarTimeSheet;
import cate.common.util.TimeTool;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@NoteClass("公会战时间表")
@Slf4j
public class GuildWarTimeTable  {

    @NoteField("当前的阶段")
    public byte period;

    @NoteField("时间<阶段，结束时间>")
    public Map<Byte, Long> timeMap;

    @NoteField(value = "下次检测时间",detail = "就是当前阶段结束的时间")
    public long checkTime;

    public void initialize() {
        if (timeMap == null) {
            timeMap = new HashMap<>();
        }
    }

    public boolean checkStart(GuildWarTimeSheet sheet) {
        long now = System.currentTimeMillis();
        int day = TimeTool.dayOfWeekCn(now);
        if (!GDGuildWar.DAY_OF_WEEK.contains(day)) {
            return false;
        }
        if (!timeMap.isEmpty()&& TimeTool.isSameDay(getStartTime(), now)) {
            return false;
        }
        checkTime = 0;
        timeMap.clear();
        long startTime = TimeTool.getZeroTimeStamp(System.currentTimeMillis());
        for (int i = 1; i <= 4; i++) {
            GuildWarTimeRow row = sheet.get(i);
            if (row != null) {
                startTime += row.minute * 60 * 1000;
            }
            timeMap.put((byte) i, startTime);
        }
        period = GDGuildWar.Period.SIGN_UP;
        checkTime = timeMap.get(period);
        printTime();
        return true;
    }

    @JsonIgnore
    private long getStartTime(){
        return timeMap.getOrDefault(GDGuildWar.Period.SIGN_UP,0L);
    }

    @JsonIgnore
    public boolean tick() {
        if (checkTime == 0 || System.currentTimeMillis() < checkTime) {
            return false;
        }
        period = GDGuildWar.Period.getNextPeriod(period);
        if (period == GDGuildWar.Period.NULL) {
            checkTime = 0;
        } else {
            checkTime = timeMap.get(period) == null ? 0 : timeMap.get(period);
        }
        printTime();
        return true;
    }

    private void printTime(){
        log.info("[公会战]阶段发生变更 目前是[{}]阶段 下次变更时间是:{}", GDGuildWar.Period.getDes(period), TimeTool.getDF2().format(new Date(checkTime)));
    }

    public void clear() {
        period = GDGuildWar.Period.NULL;
        timeMap.clear();
        checkTime = 0L;
    }
}
